import { ref, computed } from 'vue'
import { userCache, type UserInfo } from '@/utils/userCache'

// 用户状态管理
export const useUserStore = () => {
  // 响应式用户信息
  const userInfo = ref<UserInfo | null>(null)
  const isLoading = ref(false)
  
  // 计算属性
  const isLoggedIn = computed(() => !!userInfo.value)
  const isVerified = computed(() => userInfo.value?.isVerified || false)
  const isHirePerson = computed(() => userInfo.value?.isHirePerson || false)
  const userName = computed(() => userInfo.value?.name || '')
  const userAvatar = computed(() => userInfo.value?.avatar || '')
  const favoriteCount = computed(() => userInfo.value?.favoriteCount || 0)
  const employmentStatus = computed(() => userInfo.value?.employmentStatus || '未入职')
  
  /**
   * 初始化用户信息（从缓存加载）
   */
  const initFromCache = () => {
    try {
      const cachedInfo = userCache.getUserInfo()
      if (cachedInfo) {
        userInfo.value = cachedInfo
        console.log('从缓存加载用户信息成功')
      }
    } catch (error) {
      console.error('从缓存加载用户信息失败:', error)
    }
  }
  
  /**
   * 登录后初始化用户信息
   */
  const initUserInfo = (info: Partial<UserInfo>) => {
    isLoading.value = true
    try {
      // 存储到缓存
      userCache.initUserInfo(info)
      
      // 更新状态
      const fullInfo = userCache.getUserInfo()
      if (fullInfo) {
        userInfo.value = fullInfo
      }
      
      console.log('用户信息初始化成功')
    } catch (error) {
      console.error('用户信息初始化失败:', error)
    } finally {
      isLoading.value = false
    }
  }
  
  /**
   * 更新用户信息
   */
  const updateUserInfo = (updates: Partial<UserInfo>) => {
    try {
      const success = userCache.updateUserInfo(updates)
      if (success) {
        // 重新从缓存加载
        const updatedInfo = userCache.getUserInfo()
        if (updatedInfo) {
          userInfo.value = updatedInfo
        }
      }
      return success
    } catch (error) {
      console.error('更新用户信息失败:', error)
      return false
    }
  }
  
  /**
   * 更新实名认证信息
   */
  const updateVerificationInfo = (realName: string, idNumber: string) => {
    return updateUserInfo({
      realName,
      idNumber, // 明文存儲，僅展示時脫敏
      isVerified: true
    })
  }
  
  /**
   * 更新收藏数量
   */
  const updateFavoriteCount = (count: number) => {
    return updateUserInfo({ favoriteCount: count })
  }
  
  /**
   * 更新入职状态
   */
  const updateEmploymentStatus = (status: string) => {
    return updateUserInfo({ employmentStatus: status })
  }
  
  /**
   * 设置openId
   */
  const setOpenId = (openId: string) => {
    try {
      const success = userCache.setOpenId(openId)
      if (success) {
        // 重新从缓存加载
        const updatedInfo = userCache.getUserInfo()
        if (updatedInfo) {
          userInfo.value = updatedInfo
        }
      }
      return success
    } catch (error) {
      console.error('设置openId失败:', error)
      return false
    }
  }
  
  /**
   * 获取openId
   */
  const getOpenId = () => {
    return userCache.getOpenId()
  }
  
  /**
   * 登出
   */
  const logout = () => {
    try {
      userCache.clearUserInfo()
      userInfo.value = null
      console.log('用户登出成功')
    } catch (error) {
      console.error('用户登出失败:', error)
    }
  }
  
  /**
   * 获取Token
   */
  const getToken = () => {
    return userCache.getToken()
  }
  
  /**
   * 检查登录状态
   */
  const checkLoginStatus = () => {
    return userCache.isLoggedIn()
  }
  
  /**
   * 初始化默认用户信息
   */
  const initDefaultUserInfo = () => {
    userCache.initDefaultUserInfo()
  }
  
  /**
   * 手机号脱敏处理
   */
  const maskPhone = (phone: string) => {
    return userCache.maskPhone(phone)
  }
  
  return {
    // 状态
    userInfo,
    isLoading,
    
    // 计算属性
    isLoggedIn,
    isVerified,
    userName,
    userAvatar,
    favoriteCount,
    employmentStatus,
    
    // 方法
    initFromCache,
    initUserInfo,
    updateUserInfo,
    updateVerificationInfo,
    updateFavoriteCount,
    updateEmploymentStatus,
    setOpenId,
    getOpenId,
    logout,
    getToken,
    checkLoginStatus,
    initDefaultUserInfo,
    maskPhone
  }
}

// 创建全局实例
export const userStore = useUserStore() 